const http = require('http');
const url = require("url");
const util = require('util');
const querystring = require('querystring');
const host = "127.0.0.1";
const port = 3000;
const fs = require('fs');
const path = require('path');
const { createImageData, loadImage, createCanvas } = require('canvas');
const downloadpath = path.join(__dirname, './test1/');
const basePath = process.argv[2] || './designImgs/02';
const imgFolder = path.resolve(__dirname, basePath);
// console.log('basePath',basePath);
// console.log('imgFolder',imgFolder);
const imgList = fs.readdirSync(imgFolder);
// 过滤非图片文件
const filterImgList = imgList.filter((item) => {
  const reg=/(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/; 
  return reg.test(item);
});
const canvas = createCanvas(200, 200);
const ctx = canvas.getContext('2d');

// 缩小图片尺寸处理
async function shrinkingImg (folder, imgList=[]) {
    const list = await Promise.all(imgList.map( async item => {
        const oImg = await loadImage(folder+'/'+item);
        const imgWidth = 8;
        ctx.clearRect(0, 0, imgWidth, imgWidth);
        ctx.drawImage(oImg, 0, 0, imgWidth, imgWidth);
        const data = ctx.getImageData(0,0,imgWidth,imgWidth);
        return data.data;
    }));
    // console.log('list:', list);
    return list;
}

// 灰度化-比较灰度值
async function getHashList (folder, imgList) {
  const list = await shrinkingImg(folder, imgList);
  const averageList = [];
  list.forEach(item => {
    const itemList = [];
    item.forEach((newItem, index) => {
      if ((index+1)%4 === 0) {
        const newItem1 = item[index-3];
        const newItem2 = item[index-2];
        const newItem3 = item[index-1];
        const gray = (newItem1 + newItem2 + newItem3)/3;
        itemList.push(~~gray);
      }
    }); 
    const hashData = getHash(itemList);
    averageList.push(hashData);
  });
  return averageList;
}

function getHash (arr) {
  const length = arr.length;
  const average = arr.reduce((pre, next) => pre+next, 0)/length;
  return arr.map(item => item >= average ? 1 : 0).join('');
}

// 编辑距离
function strSimilarity2Number(s, t){
	let n = s.length, m = t.length, d=[];
	let i, j, s_i, t_j, cost;
	if (n == 0) return m;
	if (m == 0) return n;
	for (i = 0; i <= n; i++) {
		d[i]=[];
		d[i][0] = i;
	}
	for(j = 0; j <= m; j++) {
		d[0][j] = j;
	}
	for (i = 1; i <= n; i++) {
		s_i = s.charAt (i - 1);
		for (j = 1; j <= m; j++) {
			t_j = t.charAt (j - 1);
			if (s_i == t_j) {
				cost = 0;
			}else{
				cost = 1;
			}
		d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
		}
	}
	return d[n][m];
}

function Minimum(a,b,c){
	return a<b?(a<c?a:c):(b<c?b:c);
}

function strSimilarity2Percent(s, t){
	let l = s.length > t.length ? s.length : t.length;
	let d = strSimilarity2Number(s, t);
	return (1-d/l).toFixed(4);
}

/**
 * @description: 相似度判断
 * @param {imgList:Array[文件列表数组], limit:Number[相似度系数]}
 * @return: 相似度二维数组
 */
async function getSimilarImgList (imgList, ctrImgPath, limit=0.85) {
  // 获取模板图片索引二维数组
  const arr = await getHashList(imgFolder, imgList);
  // 获取对比图片索引二维数组
  const ctrImgFolder = path.resolve(__dirname, ctrImgPath);
  const ctrImgList = fs.readdirSync(ctrImgFolder);
  const ctrArr = await getHashList(ctrImgFolder, ctrImgList);
  //  const ctrEle = ctrArr[0];
  const array = [];
  // 已经匹配的图片无需再做遍历
  const includeList = [];
  var maxImg = 0;
  var resImg;
  for(let i = 0,len = ctrArr.length; i < len; i++) {
    var maxPer = 0;
    const ctrEle = ctrArr[i];
    for (let index = 0,length = arr.length; index < length; index++) {
        const element = arr[index];
        const list = [];

        const percent = strSimilarity2Percent(element, ctrEle);
        console.log('相似度: ', percent);
        if(percent > maxPer) {
            maxPer = percent;
        };
    }
    console.log('maxPer: ', maxPer);
    if(maxPer >= maxImg) {
        maxImg = maxPer;
        resImg = i;
    };
    // return maxPer;
  };
  console.log(`resImg: ${resImg}, maxImg: ${maxImg}`);
    
    // for (let i = index+1; i < length; i++) {
    //   const elementNext = arr[i];
    //   const percent = strSimilarity2Percent(element, elementNext);
    //   console.log('percent: ', percent);
    //   const includeItem = includeList.indexOf(i) > 0;
    //   if (percent>limit && !includeItem) {
    //     list.push(i);
    //     includeList.push(i);
    //   }
    // }
    // if (list.length) array.push([index,...list]);
    //   }
    //   const mappingArr = array.map(item=>{
    //     return item.map(index => imgList[index]);
    //   });
    //   console.log(mappingArr);
    //   return mappingArr;
}
// const imgUrl = '';

// const base64 = imgUrl.replace(/^data:\w+\/.*;base64,/, '');
// const dataBuffer = Buffer.from(base64, 'base64');
// const dataPath = downloadpath + Date.now() + '.jpg';
// fs.writeFileSync(dataPath, dataBuffer);

// getSimilarImgList(filterImgList, downloadpath, 0.64);
// fs.unlinkSync(dataPath);
// fs.rename(sourceFile, destPath, function (err) {
//   if (err) console.log(err);
// });

function toPost(req, res){
  let data = 'percent';
  req.on('data', function(chunk){    
      data += chunk;
  }); 
  req.on('end', function(){    
      // data = querystring.parse(data);
      //res.end('POST请求内容：\n' + util.inspect(data));
      data = '最高相似率：' + data;        
      res.end(data);
      console.log(data);
  });
}

http.createServer((req, res) => {
  res.statusCode = 200,
  res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  if(req.method === 'POST') {
      toPost(req, res);
  }
}).listen(port, host, () => {
  console.log(`Server listening on: http://localhost:${port}`);
});